package com.yc.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @program: cloud147
 * @description: 针对hello服务的负载均衡策略类
 * @author: zy
 * @create: 2025-07-13 15:10
 */
@Configuration
public class HelloLoadBalancerConfig {

    // environment: spring容器提供的环境对象
    // loadBalancerClientFactory: 负载均衡器工厂对象  ->工厂模式，用于创建负载均衡器对象
    @Bean  // id="randomLoadBalancer" class=""
    public ReactorLoadBalancer<ServiceInstance> rlb(Environment environment,
                                                    LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        // 上面代码 :   environment.getProperty("loadbalancer.client.name") -> hello

        return new RandomLoadBalancer(  loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class)  , name);
        // return new MyOnlyOneLoadBalancer(  loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class)  , name   );
    }
}
